import sys
import json
import os

"""解压非标准的asar文件
1. 通过匹配{}找到header json
2. 通常第一个文件是package.json,通过{找到offset基数
"""


def extract_header(data):
    count = 0
    header_json_start = 0
    header_json_end = 0

    i = 0
    while i < len(data):
        ch = data[i]
        if ch == ord('{'):
            count += 1
            if count == 1 and header_json_start == 0:
                header_json_start = i
        elif ch == ord('}'):
            count -= 1
            if count == 0:
                header_json_end = i
                break

        i += 1
    return header_json_start, header_json_end


def extract(dirname, kvmap, data):
    for k, v in kvmap.items():
        if "files" in v:
            subdir = os.path.join(dirname, k)
            if not os.path.exists(subdir):
                os.mkdir(subdir)
            extract(subdir, v["files"], data)
        else:
            try:
                offset = int(v["offset"])
                size = v["size"]
                with open(os.path.join(dirname, k), 'wb') as f:
                    f.write(
                        data[base_offset + offset: base_offset + offset + size])
            except KeyError:
                print("{}/{}".format(dirname, k), v)


data = ''
with open(sys.argv[1], 'rb') as f:
    data = f.read()

header_json_start, header_json_end = extract_header(data)
header_json = json.loads(data[header_json_start: header_json_end+1])

with open("header.json", 'wb') as f:
    f.write(data[header_json_start: header_json_end+1])

print(header_json_start)
print(header_json_end)
# print(chr(data[header_json_start]))
# print(chr(data[header_json_end]))
print(header_json_end - header_json_start)

base_offset = header_json_end + 1
# base_offset = int(header_json_start + (header_json_end - header_json_start + 1)/ 16 * 16)
print(base_offset)
while base_offset < len(data):
    if data[base_offset] == ord('{'):
        break
    base_offset += 1

print(base_offset)


rootdir = "app"
extract("", {rootdir: header_json}, data)
